package org.example.springboot.common.util;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import org.springframework.util.CollectionUtils;
import org.example.springboot.common.domain.request.PageRequest;
import org.example.springboot.common.domain.response.PageResult;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

public class PageUtil {

    public static <T> Page<T> parseRequest(PageRequest pageRequest) {
        Page<T> page = PageDTO.of(pageRequest.getCurrent(), pageRequest.getSize(), true);

        // 设置排序字段
        if (!CollectionUtils.isEmpty(pageRequest.getOrders())) {
            List<OrderItem> orders = new ArrayList<>();
            pageRequest.getOrders().forEach(thisOrder -> {
                OrderItem orderItem = null;
                if (thisOrder.isAsc()) {
                    orderItem = OrderItem.asc(thisOrder.getColumn());
                } else {
                    orderItem = OrderItem.desc(thisOrder.getColumn());
                }
                orders.add(orderItem);
            });
            page.setOrders(orders);
        }
        return page;
    }

    public static <T> PageResult<T> parseResult(Page<T> pageDTO) {
        PageResult<T> pageResult = new PageResult<>();
        pageResult.setSize((int) pageDTO.getSize());
        pageResult.setCurrent((int) pageDTO.getCurrent());
        pageResult.setTotal(pageDTO.getTotal());
        pageResult.setData(pageDTO.getRecords());
        return pageResult;
    }

    public static <T, R> PageResult<R> parseResult(Page<T> pageDTO, Function<T, R> mapper) {
        PageResult<R> pageResult = new PageResult<>();
        pageResult.setSize((int) pageDTO.getSize());
        pageResult.setCurrent((int) pageDTO.getCurrent());
        pageResult.setTotal(pageDTO.getTotal());
        pageResult.setData(pageDTO.getRecords().stream().map(mapper).collect(Collectors.toList()));
        return pageResult;
    }
}
